package com.chijun.mform.create.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.chijun.mform.R;
import com.chijun.mform.create.dialog.ISelectShenPiJieDianType;
import com.chijun.mform.create.dialog.ProcessInstallDialog;
import com.chijun.mform.create.dialog.SelectProcessTypeDialog;
import com.chijun.mform.create.fragment.FormAddProcessFragment;
import com.chijun.mform.create.mode.FormApprovePerson;
import com.chijun.mform.create.mode.FormApproveProcess;
import com.chijun.mform.create.mode.FormConfig;
import com.example.ccj.u.GenerateId;
import com.example.ccj.u.LogUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


/**
 * 审批流程节点Adapter
 * 含增删改
 * 点击字段后返回字段类型id
 * 2024年11月10日23:38:06
 */
public class ShowProcessAdapter extends RecyclerView.Adapter<ShowProcessAdapter.ViewHolder>{
    FormConfig formConfig;

    List<FormApproveProcess> formApproveProcessList;


    /**
     *
     *
     * @param formConfig 表单配置
     */
    public ShowProcessAdapter(FormConfig formConfig){
        this.formConfig = formConfig;
        this.formApproveProcessList = formConfig.getFormApproveProcessList();
    }

    @NonNull
    @Override
    public ShowProcessAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ShowProcessAdapter.
                ViewHolder(LayoutInflater.from(parent.getContext()).
                inflate(R.layout.adapater_select_process, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull ShowProcessAdapter.ViewHolder holder, int position) {

        holder.id.setText(String.valueOf(position+1));
        FormApproveProcess formApproveProcess = formApproveProcessList.get(position);

        //根据审批节点类型设置整体视图
        installOverallView(holder,formApproveProcess);

        //根据审批人选择类型设置审批人选择视图
        installShenPiRenView(holder,formApproveProcess);

        installProcessTypeView(holder,formApproveProcess);

        final int po = position;
        //删除审批节点
        holder.deleteImg.setOnClickListener(v -> notifyRemove(po));
        //添加审批节点
        holder.addImg.setOnClickListener(v -> add(holder,po));
        //设置审批节点
        holder.allLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //是否包含审批人权限设置map不包含添加新的
                if (!formConfig.getApproveFieldPermissionMap().containsKey(formApproveProcess.id)) formConfig.getApproveFieldPermissionMap().put(formApproveProcess.id,new HashMap<>());
                //是否包含审批人员列表map不包含添加新的
                if (!formConfig.getFormApprovePersonMap().containsKey(formApproveProcess.id)) formConfig.getFormApprovePersonMap().put(formApproveProcess.id,new HashMap<>());
                //打开该流程节点的配置界面
                ProcessInstallDialog processInstallDialog
                        = new ProcessInstallDialog(holder.allLl.getContext(),po,
                        formConfig.getFormFieldList(), formApproveProcess,
                        formConfig.getApproveFieldPermissionMap().get(formApproveProcess.id),
                        formConfig.getFormApprovePersonMap().get(formApproveProcess.id),
                        () -> {
                            notifyItemChanged(po);
                        });
                processInstallDialog.show();
            }
        });
    }

    private String getPeronNmeSet(Map<String, FormApprovePerson> stringFormApprovePersonMap){
        StringBuilder stringBuilder = new StringBuilder();
        if (stringFormApprovePersonMap != null) {
            Iterator<FormApprovePerson> iterator = stringFormApprovePersonMap.values().iterator();
            while (iterator.hasNext()) {
                FormApprovePerson next = iterator.next();
                stringBuilder.append(next.personName);
                if (iterator.hasNext()) stringBuilder.append(",");
            }
        }
        return stringBuilder.toString();
    }

    /**
     * 审批人选择视图
     * @param holder 1
     * @param formApproveProcess 当前流程
     */
    private void installShenPiRenView(@NonNull ShowProcessAdapter.ViewHolder holder,FormApproveProcess formApproveProcess ){
        Map<String, FormApprovePerson> stringFormApprovePersonMap = formConfig.getFormApprovePersonMap().get(formApproveProcess.id);
        //审批人类型视图显示
        //配置审批人时显示内容
        if (stringFormApprovePersonMap != null && !stringFormApprovePersonMap.isEmpty()) {
            if ( stringFormApprovePersonMap.size() > 2) {
                holder.typeText.setText("多人");
            } else {
                String peronNmeSet = getPeronNmeSet(stringFormApprovePersonMap);
                holder.typeText.setText(peronNmeSet);
            }
        } else {
            //未配置审批人时显示内容
            //审批人选择类型：指定人员
            if (formApproveProcess.personType == FormAddProcessFragment.APPROVAL_SELECT_MODE_ZHI_DING) {
                //未指定审批人时提示选择审批人
                 holder.typeText.setText(FormAddProcessFragment.ZD);
                //审批人选择类型：发起人自己
            } else if (formApproveProcess.personType == FormAddProcessFragment.APPROVAL_SELECT_MODE_FA_QI_REN_ZI_JI) {
                holder.typeText.setText(FormAddProcessFragment.FQR);
                //审批人选择类型：发起人自选
            } else if (formApproveProcess.personType == FormAddProcessFragment.APPROVAL_SELECT_MODE_FA_QI_REN_XUAN_ZE){
                holder.typeText.setText(FormAddProcessFragment.FQRS);
            }
        }
    }

    /**
     * 设置审批方式视图
     */
    private void installProcessTypeView(@NonNull ShowProcessAdapter.ViewHolder holder,FormApproveProcess formApproveProcess){
        //会签，或签显示
        holder.processType.setVisibility(View.VISIBLE);
        if (formApproveProcess.duoRenShenPiFangShi == FormAddProcessFragment.APPROVAL_MODE_HUI_QIAN) {
            holder.processType.setText("会");
        } else if (formApproveProcess.duoRenShenPiFangShi == FormAddProcessFragment.APPROVAL_MODE_HUO_QIAN) {
            holder.processType.setText("或");
        } else if (formApproveProcess.duoRenShenPiFangShi == FormAddProcessFragment.APPROVAL_MODE_YI_CI_SHEN_PI) {
            holder.processType.setText("依");
        } else if (formApproveProcess.duoRenShenPiFangShi == FormAddProcessFragment.APPROVAL_MODE_ZI_JI) {
            holder.processType.setText("自");
        }else {
            holder.processType.setText("错");
        }
    }

    /**
     * 设置整体视图
     * @param holder
     * @param formApproveProcess
     */
    private void installOverallView(@NonNull ShowProcessAdapter.ViewHolder holder,FormApproveProcess formApproveProcess ){
        //发起人视图
        if (formApproveProcess.type == FormAddProcessFragment.FA_QI_REN_JIE_DIAN) {
            holder.allLl.setBackgroundResource(R.drawable.form_process_fa_qi_ren_all);
            holder.titleLl.setBackgroundResource(R.drawable.form_process_fa_qi_ren_title);
            holder.titleText.setText("发起人");
            holder.titleImg.setImageResource(R.drawable.fa_qi_ren_white);
            holder.typeText.setText("发起人");
            holder.deleteImg.setVisibility(View.GONE);
            //审批人视图
        } else if (formApproveProcess.type == FormAddProcessFragment.SHEN_PI_REN_JIE_DIAN) {
            holder.allLl.setBackgroundResource(R.drawable.form_process_shen_pi_ren_all);
            holder.titleLl.setBackgroundResource(R.drawable.form_process_shen_pi_ren_title);
            holder.titleText.setText("审批人");
            holder.titleImg.setImageResource(R.drawable.shen_pi_ren_white);
            holder.deleteImg.setVisibility(View.VISIBLE);
            //抄送人视图
        } else if (formApproveProcess.type == FormAddProcessFragment.CHAO_SONG_REN_JIE_DIAN) {
            holder.allLl.setBackgroundResource(R.drawable.form_process_chao_song_ren_all);
            holder.titleLl.setBackgroundResource(R.drawable.form_process_chao_song_ren_title);
            holder.titleText.setText("抄送人");
            holder.titleImg.setImageResource(R.drawable.chao_song_ren_white);
            holder.deleteImg.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 添加节点
     * @param holder
     * @param position
     */
    private void add(ShowProcessAdapter.ViewHolder holder,int position){
        SelectProcessTypeDialog selectProcessTypeDialog = new SelectProcessTypeDialog(holder.addImg.getContext(), new ISelectShenPiJieDianType() {
            @Override
            public void result(int type) {
                FormApproveProcess process = new FormApproveProcess();
                LogUtils.d("当前插入位置：" + position);
                process.type = type;
                process.personType = FormAddProcessFragment.APPROVAL_SELECT_MODE_ZHI_DING;
                process.id = GenerateId.getId();
                process.formId = formConfig.getForm().id;
                process.duoRenShenPiFangShi = FormAddProcessFragment.APPROVAL_MODE_HUI_QIAN;
                if (type == FormAddProcessFragment.SHEN_PI_REN_JIE_DIAN) {
                    process.name = "审批人";
                } else if (type == FormAddProcessFragment.CHAO_SONG_REN_JIE_DIAN) {
                    process.name = "抄送人";
                }
                formApproveProcessList.add(position+1,process);
                notifyItemInserted(position+1);
                notifyItemRangeChanged(position+1,formApproveProcessList.size()-position+1);//通知数据与界面重新绑定
            }
        });

        selectProcessTypeDialog.show();
    }

    /**
     * 删除节点
     * @param position
     */
    private void notifyRemove(int position){
        FormApproveProcess remove = formApproveProcessList.remove(position);
        notifyItemRemoved(position);
        //重新加载从删除位置往下的所有item，如果删除的是中间，自删除的位置到最后开始是做重新添加操作
        //避免下表越界等错误
        notifyItemRangeRemoved(position,getItemCount());
        //清除该审批所关联的审批人
        formConfig.getFormApprovePersonMap().remove(remove.id);
    }



    @Override
    public int getItemCount() {
        return formApproveProcessList == null ? 0 : formApproveProcessList.size();
    }

    public static class ViewHolder extends  RecyclerView.ViewHolder{
        private final TextView titleText,typeText,processType,id;
        private final ImageView titleImg,deleteImg,addImg;
        private final LinearLayout allLl,titleLl;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            allLl = itemView.findViewById(R.id.adapater_select_process_install);
            titleLl = itemView.findViewById(R.id.adapater_select_process_title);
            titleImg = itemView.findViewById(R.id.adapater_select_process_title_img);
            titleText = itemView.findViewById(R.id.adapater_select_process_title_text);
            deleteImg = itemView.findViewById(R.id.adapater_select_process_delete);
            typeText = itemView.findViewById(R.id.adapater_select_process_text);
            addImg = itemView.findViewById(R.id.adapater_select_process_add);
            processType = itemView.findViewById(R.id.adapater_select_process_process_type_text);
            id = itemView.findViewById(R.id.adapater_select_process_id);
        }
    }

    public interface IInstallListener{
        void result();
    }
}
